<?php

namespace app\merchant\model;

use app\common\model\Goods as GoodsModel;
use app\merchant\model\Wxapp as WxappModel;
use app\store\service\Goods as GoodsService;

/**
 * 商品模型
 * Class Goods
 * @package app\store\model
 */
class Goods extends GoodsModel
{



    /**
     * 表单验证
     * @param $data
     * @return bool|false|int
     * @throws \think\exception\DbException
     */
    private function validateForm($data)
    {

        //获取分销方案
        $wxapp_id = self::$wxapp_id;
        //获取分销方案
        $dealerCase = WxappModel::dealerCase($wxapp_id);

        if(!isset($data['goods_name']) || empty($data['goods_name'])){
            $this->error = '请输入商品名称';
            return false;
        }

        if(!isset($data['category_id']) || empty($data['category_id'])){
            $this->error = '请选择商品分类';
            return false;
        }

        if(!isset($data['images']) || empty($data['images'])){
            $this->error = '请选择商品图片';
            return false;
        }

        if(!isset($data['spec_type']) || empty($data['spec_type'])){
            $this->error = '请选择商品规格';
            return false;
        }

        //单规格
        if($data['spec_type']==10){
            if(!isset($data['sku']) || empty($data['sku'])){
                $this->error = '请输入规格参数';
                return false;
            }
            if(!isset($data['sku']['goods_price']) || isZeroNumeric($data['sku']['goods_price'])){
                $this->error = '商品价格不合法';
                return false;
            }
            if(bccomp($data['sku']['goods_price'], '5000', 2) == 1) {
                $this->error = '商品价格不能大于5000元';
                return false;
            }

            if(!isset($data['sku']['stock_num']) || isZeroNumeric($data['sku']['stock_num'])){
                $this->error = '商品库存不合法';
                return false;
            }

            if(!isset($data['sku']['goods_weight']) || isZeroNumeric($data['sku']['goods_weight'])){
                $this->error = '商品重量不合法';
                return false;
            }

        }

        //多规格
        if($data['spec_type']==20){

            if(!isset($data['spec_many']) || empty($data['spec_many'])){
                $this->error = '规格设置错误';
                return false;
            }

//            $spec_items = [];
//            foreach ($data['spec_many']['spec_attr'] as $item) {
//                 foreach($item['spec_items'] as $k=>&$v){
//                     $spec_items[] = [
//                         'item_id'=>$v['item_id'],
//                         'spec_value'=>$v['spec_value'],
//                     ];
//                 }
//            }
//            pre($spec_items);
//
//            if(!isset($data['sku']['goods_price']) || isZeroNumeric($data['sku']['goods_price'])){
//                $this->error = '商品价格不合法';
//                return false;
//            }
//            if(bccomp($data['sku']['goods_price'], '5000', 2) == 1) {
//                $this->error = '商品价格不能大于5000元';
//                return false;
//            }
//
//            if(!isset($data['sku']['stock_num']) || isZeroNumeric($data['sku']['stock_num'])){
//                $this->error = '商品库存不合法';
//                return false;
//            }
//
//            if(!isset($data['sku']['goods_weight']) || isZeroNumeric($data['sku']['goods_weight'])){
//                $this->error = '商品重量不合法';
//                return false;
//            }

        }

        //库存计算方式(10下单减库存 20付款减库存)
        if(!isset($data['deduct_stock_type']) || empty($data['deduct_stock_type'])){
            $this->error = '请选择库存计算方式';
            return false;
        }

        //商品详情
        if(!isset($data['content']) || empty($data['content'])){
            $this->error = '请输入商品详情';
            return false;
        }

        //运费模板
        if(!isset($data['delivery_id']) || empty($data['delivery_id'])){
            $this->error = '请选择运费模板';
            return false;
        }

        //虚拟商品 是否为虚拟物品 1是 2不是
        if(!isset($data['is_fictitious']) || empty($data['is_fictitious'])){
            $this->error = '请选择是否虚拟商品';
            return false;
        }

        //商品状态 商品状态(10上架 20下架)
        if(!isset($data['goods_status']) || empty($data['goods_status'])){
            $this->error = '请选择商品状态';
            return false;
        }

        //初始销量
        if(!isset($data['sales_initial']) || isZeroNumeric($data['sales_initial'])){
            $this->error = '初始销量不合法';
            return false;
        }

        //商品排序
        if(!isset($data['goods_sort']) || isZeroNumeric($data['goods_sort'])){
            $this->error = '商品排序不合法';
            return false;
        }

        if($dealerCase==1){
            //分销佣金类型
            if(!isset($data['dealer_money_type']) || empty($data['dealer_money_type'])){
                $this->error = '请选择分销佣金类型';
                return false;
            }
            if(!isset($data['first_money']) || isZeroNumeric($data['first_money'])){
                $this->error = '分销佣金不合法';
                return false;
            }
        }

        return true;
    }

    /**
     * 添加商品
     * @param array $data
     * @return bool
     * @throws \think\exception\PDOException
     */
    public function add(array $data)
    {

        // 表单验证
        if (!$this->validateForm($data)) {
            return false;
        }

        $data['wxapp_id'] = $data['sku']['wxapp_id'] = self::$wxapp_id;

        // 开启事务
        $this->startTrans();
        try {
            $data['is_ind_dealer']=1;
            // 添加商品
            $this->allowField(true)->isUpdate(false)->save($data);
            // 商品规格
            $this->addGoodsSpec($data);
            // 商品图片
            $this->addGoodsImages($data['images']);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }

    /**
     * 编辑商品
     * @param $data
     * @return bool|mixed
     */
    public function edit($data)
    {

        // 表单验证
        if (!$this->validateForm($data)) {
            return false;
        }

        $data['wxapp_id'] = $data['sku']['wxapp_id'] = self::$wxapp_id;
        return $this->transaction(function () use ($data) {
            // 保存商品
            $data['is_ind_dealer']=1;
            $this->allowField(true)->save($data);
            // 商品规格
            $this->addGoodsSpec($data, true);
            // 商品图片
            $this->addGoodsImages($data['images']);
            return true;
        });
    }

    /**
     * 添加商品图片
     * @param $images
     * @return int
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    private function addGoodsImages($images)
    {
        $this->image()->delete();
        $data = array_map(function ($image_id) {
            return [
                'image_id' => $image_id,
                'wxapp_id' => self::$wxapp_id
            ];
        }, $images);
        return $this->image()->saveAll($data);
    }



    /**
     * 添加商品规格
     * @param $data
     * @param $isUpdate
     * @throws \Exception
     */
    private function addGoodsSpec($data, $isUpdate = false)
    {

        // 更新模式: 先删除所有规格
        $model = new GoodsSku;
        $isUpdate && $model->removeAll($this['goods_id']);
        // 添加规格数据
        if ($data['spec_type'] == '10') {
            // 单规格
            $this->sku()->save($data['sku']);
        } else if ($data['spec_type'] == '20') {
            // 添加商品与规格关系记录
            $model->addGoodsSpecRel($this['goods_id'], $data['spec_many']['spec_attr']);

            // 添加商品sku
            $model->addSkuList($this['goods_id'], $data['spec_many']['spec_list']);

        }
    }

    /**
     * 修改商品状态
     * @param $state
     * @return false|int
     */
    public function setStatus($state)
    {

        return $this->allowField(true)->save(['goods_status' => $state]) !== false;
    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        if (!GoodsService::checkIsAllowDelete($this['goods_id'])) {
            $this->error = '当前商品正在参与其他活动，不允许删除';
            return false;
        }
        return $this->allowField(true)->save(['is_delete' => 1]);
    }

    /**
     * 获取当前商品总数
     * @param array $where
     * @return int|string
     * @throws \think\Exception
     */
    public function getGoodsTotal($where = [])
    {
        return $this->where('is_delete', '=', 0)->where($where)->count();
    }

}
